package com.gxwgy.wg2404.controller;

import com.gxwgy.wg2404.pojo.UsersPojo;
import com.gxwgy.wg2404.util.DBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author 姚相国
 * @version 1.0
 * @className AdminEditUserServlet
 * @date 2024/12/18 15:46
 */
@WebServlet("/administrator/editUser")
public class AdminEditUserServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取当前登录的用户名（必须是管理员）
        HttpSession session = request.getSession();
        Object username = session.getAttribute("username");

        if (username == null || (!"root".equals(username) && !"admin1".equals(username))) {
            response.sendRedirect(request.getContextPath() + "/index.jsp");  // 如果不是管理员，跳转到首页
            return;
        }

        // 获取用户 ID，判断是否传递了 ID 参数
        String userIdStr = request.getParameter("id");
        if (userIdStr == null || userIdStr.isEmpty()) {
            response.sendRedirect(request.getContextPath() + "/error.jsp");
            return;
        }

        int userId = Integer.parseInt(userIdStr);

        // 从数据库获取用户信息
        UsersPojo user = getUserById(userId);

        if (user != null) {
            // 将用户信息传递给 JSP 页面
            request.setAttribute("user", user);
            request.getRequestDispatcher("/editUsers.jsp").forward(request, response);
        } else {
            response.sendRedirect(request.getContextPath() + "/error.jsp");
        }
    }

    // 获取用户信息的方法
    private UsersPojo getUserById(int userId) {
        UsersPojo user = null;
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM users WHERE id = ?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, userId);
            rs = ps.executeQuery();

            if (rs.next()) {
                user = new UsersPojo();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setEmail(rs.getString("email"));
                user.setRole(rs.getString("role"));
                user.setCreated_at(rs.getString("created_at"));
                user.setUpdated_at(rs.getString("updated_at"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, ps, rs);
        }
        return user;
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取当前登录的用户名（必须是管理员）
        HttpSession session = request.getSession();
        Object username = session.getAttribute("username");

        if (username == null || (!"root".equals(username) && !"admin1".equals(username))) {
            response.sendRedirect(request.getContextPath() + "/index.jsp");  // 如果不是管理员，跳转到首页
            return;
        }

        // 获取编辑后的用户信息
        int userId = Integer.parseInt(request.getParameter("userId"));
        String usernameEdit = request.getParameter("username");
        String email = request.getParameter("email");
        String role = request.getParameter("role");

        // 更新用户信息
        boolean updateSuccess = updateUser(userId, usernameEdit, email, role);

        if (updateSuccess) {
            // 更新成功后，跳转到用户列表页面
            response.setContentType("text/html; charset=UTF-8");
            response.getWriter().println("<script>alert('用户信息更新成功！'); location.href='" + request.getContextPath() + "/admin/dashboard';</script>");
        } else {
            // 更新失败，返回错误页面
            response.sendRedirect(request.getContextPath() + "/error.jsp");
        }
    }

    // 更新用户信息的方法
    private boolean updateUser(int userId, String username, String email, String role) {
        Connection conn = null;
        PreparedStatement ps = null;
        boolean isSuccess = false;

        try {
            conn = DBUtil.getConnection();
            String sql = "UPDATE users SET username = ?, email = ?, role = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2, email);
            ps.setString(3, role);
            ps.setInt(4, userId);

            int rowsAffected = ps.executeUpdate();
            if (rowsAffected > 0) {
                isSuccess = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, ps, null);
        }
        return isSuccess;
    }
}

